<template>
  <div class="page-scan">
    
    <!-- 扫码区域 -->
    <video
      ref="video"
      id="video"
      :width="width"
      :height="height"
      class="scan-video"
      autoplay
    ></video>
    <!-- 提示语 -->
    <audio
      id="scanAudioTip"
      controls="controls"
      hidden
      :src="audioTip"
      ref="audio"
    ></audio>
  </div>
</template>

<script>
import { BrowserMultiFormatReader } from "@zxing/library";

export default {
  name: "scanCodePage",
  props: {
    //定义组件对外属性
    width: String,
    height: String,
  },
  data() {
    //定义属性
    return {
      loadingShow: false,
      codeReader: null,
      scanText: "", //获取扫码的数据
      vin: null,
      tipMsg: "正在尝试识别....",
      tipShow: false,
      audioTip:require("@/assets/media/tishi.mp3")//"@/assets/media/tishi.mp3"
    };
  },
  created() {
    this.codeReader = new BrowserMultiFormatReader();
    this.openScan();
  },
  destroyed() {
    this.codeReader.reset();
  },
  watch: {
    $route(to, from) {
      if (to.path == "/scanCodePage") {
        this.codeReader = new BrowserMultiFormatReader();
        this.openScanTwo();
      }
    },
  },
  methods: {
    playTip() {
      this.$refs.audio.currentTime = 0; //从头开始播放提示音
      this.$refs.audio.play(); //播放
    },
    updateOutData(data){
      //调用父组件的方法，在父组件调用子组件时，标签定义方法为 @addDataToList
      this.$emit('addDataText',data);
    },
    async openScan() {
      this.codeReader
        .getVideoInputDevices()
        .then((videoInputDevices) => {
          this.tipShow = true;
          this.tipMsg = "正在调用摄像头...";
          console.log("videoInputDevices", videoInputDevices);
          // 默认获取第一个摄像头设备id
          let firstDeviceId = videoInputDevices[0].deviceId;
          // 获取第一个摄像头设备的名称
          const videoInputDeviceslablestr = JSON.stringify(
            videoInputDevices[0].label
          );
          if (videoInputDevices.length > 1) {
            // 判断是否后置摄像头
            if (videoInputDeviceslablestr.indexOf("back") > -1) {
              firstDeviceId = videoInputDevices[0].deviceId;
            } else {
              firstDeviceId = videoInputDevices[1].deviceId;
            }
          }
          this.decodeFromInputVideoFunc(firstDeviceId);
        })
        .catch((err) => {
          this.tipShow = false;
          console.error(err);
        });
    },
    async openScanTwo() {
      this.codeReader = await new BrowserMultiFormatReader();
      this.codeReader
        .getVideoInputDevices()
        .then((videoInputDevices) => {
          this.tipShow = true;
          this.tipMsg = "正在调用摄像头...";
          console.log("videoInputDevices", videoInputDevices);
          // 默认获取第一个摄像头设备id
          let firstDeviceId = videoInputDevices[0].deviceId;
          // 获取第一个摄像头设备的名称
          const videoInputDeviceslablestr = JSON.stringify(
            videoInputDevices[0].label
          );
          if (videoInputDevices.length > 1) {
            // 判断是否后置摄像头
            if (videoInputDeviceslablestr.indexOf("back") > -1) {
              firstDeviceId = videoInputDevices[0].deviceId;
            } else {
              firstDeviceId = videoInputDevices[1].deviceId;
            }
          }
          this.decodeFromInputVideoFunc(firstDeviceId);
        })
        .catch((err) => {
          this.tipShow = false;
          console.error(err);
        });
    },
    decodeFromInputVideoFunc(firstDeviceId) {
      this.codeReader.reset(); // 重置
      this.scanText = "";
      //多种码解码方法：decodeFromVideoDevice ，官网：https://github.com/zxing-js/library/blob/master/docs/examples/multi-camera/index.html
      //国内网上写教程的是大傻逼
      this.codeReader.decodeFromVideoDevice(
        firstDeviceId,
        "video",
        (result, err) => {
          this.tipMsg = "正在尝试识别...";
          this.scanText = "";
          if (result) {
            this.playTip();
            console.log("扫描结果", result);
            this.scanText = result.text;
            if (this.scanText) {
              this.tipShow = false;
              //这里根据条形码查询产品信息，并加入到store中存储，这里模拟数据
              
              var item = {                
                Qrcode:this.scanText,                
              };
              //将数据从子组件传递给父组件
              this.updateOutData(item);
              //将模拟数据加入store中
              //this.$store.commit("SET_NEW_DATA", item);
              //console.log("已扫描的小票列表", this.$store.state.product);
            }
          }
          if (err && !err) {
            this.tipMsg = "识别失败";
            setTimeout(() => {
              this.tipShow = false;
            }, 2000);
            console.error(err);
          }
        }
      );
    },
  },
};
</script>

<style scoped>

</style>
